var uploadImage = require('../../utils/uploadFile.js');
import {
  addCrawl,
  editCrawl,
  getSingleCrawl
} from '../../api/crawl.js'
import {
  getLineList
} from '../../api/common.js'
Page({
  data: {
    form: {
      description: null,
      imageList: [],
      lineId: null,
      priceList: [],
      productName: null,
      supplierAddress: null,
      supplierName: null,
      supplierPhone: null,
    },
    options: null,
    lineList: [],
    slideButtons: [{
      type: 'warn',
      text: '删除',
      extClass: 'test',
    }],
    dialogForm: {
      maxNum: null,
      minNum: null,
      price: null,
    },
    imgAllCount: 10,
    textareaAllCount: 200,
    textareaCount: 0,
    priceAllCount: 3,
    priceCount: 0,
    lineIndex: 0,
    showActionsheet: false,
    isShowSheet: false,
    openSheet: '',
    contentAnimate: null,
    masterAnimate: null,
    tabList: ['小于', '范围', '大于'],
    activeName: '范围',
    minString: '≤',
    maxString: '≥',
    editPriceIndex: -1,
    rules: [],
    priceList: [],
    error: null,
    rules: [{
      name: 'productName',
      rules: {
        required: true,
        message: '请输入名称'
      },
    }],
    KeyboardKeys: [1, 2, 3, 4, 5, 6, 7, 8, 9, '-', 0, '×'],
    keyShow: false,
    isAddOne: true,
    isPrice: true,
    isFocus: false,
  },
  onLoad(options) {
    console.log('options', options)
    this.setData({
      options: options,
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this),
    })
    if (options.type == 'add') {
      wx.setNavigationBarTitle({
        title: '创建商品'
      })
    } else if (options.type == 'edit') {
      wx.setNavigationBarTitle({
        title: '编辑商品'
      })
    }
    this.getList();
  },
  // 提交
  submit() {
    if (!this.data.isAddOne) {
      return
    }
    if(this.data.lineIndex == 0){
      this.setData({
        error: '请选择产品线'
      })
      return
    }
    if(this.data.form.supplierPhone){
      var phone = this.data.form.supplierPhone;
      if (!(/^1[34578]\d{9}$/.test(phone))) {
        if (phone.length > 11 || phone.length == 11) {
          wx.showToast({
            title: '手机号不合法，请检查',
            icon: 'none',
            duration: 2000
          })
          return
        }
      } 
    }
    this.setData({
      [`form.lineId`]: this.data.lineIndex != 0 ? this.data.lineList[this.data.lineIndex].id : null
    });
    this.selectComponent('#ruleForm').validate((valid, errors) => {
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {
        this.setData({ isAddOne: false });
        if (this.data.options.type == 'add') {
          // 新增
          var imageList = [];
          for (let l of this.data.form.imageList) {
            imageList.push(l.imageUrl);
          }
          this.setData({
            [`form.imageList`]: imageList
          })
          addCrawl(this.data.form).then(res => {
            wx.showToast({
              title: res.msg,
              icon: 'success',
            })
            setTimeout(function() {
              wx.navigateTo({
                url: '/pages/crawlList/crawlList',
              })
            }, 500)
          }).catch(err => {

          })
        } else if (this.data.options.type == 'edit') {
          // 编辑
          editCrawl(this.data.options.id, this.data.form).then(res => {
            wx.showToast({
              title: res.msg,
              icon: 'success',
            })
            setTimeout(function() {
              wx.navigateTo({
                url: '/pages/crawlList/crawlList',
              })
            }, 500)
          }).catch(err => {

          })
        }
      }
    })
  },
  // 获取详情
  getInfo(id) {
    getSingleCrawl(id).then(res => {
      res.data.priceList = JSON.parse(JSON.stringify(res.data.priceVoList));
      var lineIndex = 0;
      for (let i = 0; i < this.data.lineList.length; i++) {
        if (this.data.lineList[i].id == res.data.lineId) {
          lineIndex = i;
          break;
        }
      }
      for (let j = 0; j < res.data.imageList.length; j++) {
        res.data.imageList[j].url = res.data.imageList[j].imageUrl;
      }
      console.log('res.data', res.data)
      this.setData({
        form: JSON.parse(JSON.stringify(res.data)),
        textareaCount: res.data.description ? res.data.description.length : 0,
        lineIndex: lineIndex,
      });
    }).catch(err => {

    })
  },
  chooseImage: function(e) {
    if (this.data.imgAllCount - this.data.form.imageList.length == 0 ){
      wx.showToast({
        title: '最多上传十张图片',
        icon: 'none',
        duration: 2000
      })
      return
    }
    var that = this;
    wx.chooseImage({
      count: that.data.imgAllCount - that.data.form.imageList.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.uplaodFile(res);
      }
    })
  },
  // 预览图片
  previewImage: function(e) {
    let index = e.target.dataset.index;
    var arr = [];
    for (let l of this.data.form.imageList) {
      arr.push(l.imageUrl);
    }
    wx.previewImage({
      current: arr[index], // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  //长按删除图片
  deleteImg: function(e) {
    var that = this;
    var tempFilePaths = that.data.form.imageList;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function(res) {
        if (res.confirm) {
          //console.log('点击确定了');
          tempFilePaths.splice(index, 1);
          that.setData({
            [`form.imageList`]: tempFilePaths
          });
        } else if (res.cancel) {
          //console.log('点击取消了');
          return false;
        }
      }
    })
  },
  selectFile(files) {
    // 返回false可以阻止某次文件上传
  },
  uplaodFile(files) {
    console.log('测试')
    var that = this;
    return new Promise((resolve, reject) => {
      for (var file of files.tempFilePaths) {
        console.log('测试', file)
        wx.compressImage({
          src: file, // 图片路径
          quality: 10,
          // 压缩质量
          success: function(res) {
            console.log('压缩', res)
            uploadImage(res.tempFilePath, function(result) {
              console.log("======上传成功图片地址为：", result, that.data.form.imageList);
              var arr = [];
              arr[0] = {
                url: result,
                imageUrl: result
              };
              var tempImgPaths = that.data.form.imageList.concat(arr);
              that.setData({
                [`form.imageList`]: tempImgPaths
              })
              wx.hideLoading();
            }, function(result) {
              console.log("======上传失败======", result);
              wx.hideLoading()
            })
          }
        })
      }
    })
  },
  uploadError(e) {
    console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail)
  },
  // 聚焦
  formFocusChange(e){
    this.setData({
      keyShow: true
    });
  },
  // 输入
  formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    if (this.data.isShowSheet) {
      this.setData({
        [`dialogForm.${field}`]: e.detail.value
      })
    } else {
      if (field == "supplierPhone") {
        let that = this
        var phone = e.detail.value;
        if (!(/^1[34578]\d{9}$/.test(phone))) {
          if (phone.length > 11 || phone.length == 11) {
            wx.showToast({
              title: '手机号不合法，请检查',
              icon: 'none',
              duration: 2000
            })
          }
        }
        this.setData({
          [`form.${field}`]: e.detail.value
        })
      } else {
        this.setData({
          [`form.${field}`]: e.detail.value
        })
      }
    }
  },
  // 选择产品线
  bindlineChange(e) {
    console.log('picker account 发生选择改变，携带值为', e.detail.value);
    this.setData({
      lineIndex: e.detail.value
    })
  },
  // 文本域描述
  textareaInput(e) {
    console.log('ee',e)
    this.setData({
      [`form.description`]: e.detail.value,
      textareaCount: e.detail.cursor
    })
  },
  bindContentFocus(e) {
    this.setData({
      isFocus: true,
    })
  },
  bindContentBlur(e) {
    this.setData({
      isFocus: false,
    })
  },
  // 价格
  // 添加价格
  addPrice() {
    var obj = {
      maxNum: null,
      minNum: null,
      price: null,
    };
    this.setData({
      editPriceIndex: -1,
      dialogForm: obj,
      isPrice: true,
    });
    console.log('点击，增加价格')
    this.__showMaster();
  },
  // 编辑
  editCrawlPrice(e) {
    var index = e.currentTarget.dataset.index;
    var obj = this.data.form.priceList[index];
    this.setData({
      editPriceIndex: index,
      dialogForm: obj,
      isPrice: true,
    });
    this.__showMaster();
    console.log('编辑价格,index', e, index)
  },
  // 确定新增或修改价格
  addPriceConfirm() {
    if (!this.data.isPrice){
      return
    }
    if (this.data.dialogForm.price === null || this.data.dialogForm.price === ''){
      wx.showToast({
        title: '价格必填！',
        icon: 'none',
        duration: 2000
      })
      return
    }else{
      var price = this.data.dialogForm.price + '';
      if (price.indexOf('.') != -1 && price.split('.')[1].length>2){
        wx.showToast({
          title: '价格最多保留两位小数！',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
    if ((this.data.dialogForm.minNum !== null && this.data.dialogForm.minNum !== '') && (this.data.dialogForm.maxNum !== null && this.data.dialogForm.maxNum !== '') &&
      this.data.dialogForm.minNum * 1 > this.data.dialogForm.maxNum * 1){
      wx.showToast({
        title: '最小数量不能比最大数量大！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    var arr = JSON.parse(JSON.stringify(this.data.form.priceList));
    if (this.data.editPriceIndex == -1) {
      // 新增
      arr.push(this.data.dialogForm)
    } else {
      // 修改
      arr[this.data.editPriceIndex] = JSON.parse(JSON.stringify(this.data.dialogForm));
    }
    this.setData({
      [`form.priceList`]: arr,
    });
    this.setData({
      isShowSheet: false,
      isPrice: false,
    })
    // this.__closeMaster();
  },
  // 删除
  slideButtonTap(e) {
    var index = e.currentTarget.dataset.index;
    var arr = JSON.parse(JSON.stringify(this.data.form.priceList));
    arr.splice(index, 1);
    this.setData({
      [`form.priceList`]: arr,
    });
  },
  // 虚拟键盘
  //点击界面键盘消失
  hindKeyboard() {
    this.setData({
      keyShow: false,
      isShowSheet: false,
    });
  },
  //点击输入框，键盘显示
  showKeyboard() {
    this.setData({
      keyShow: true
    });
  },
  keyTap(e) {
    let keys = e.currentTarget.dataset.keys,
      content = this.data.form.supplierPhone ? this.data.form.supplierPhone : '',
      len = content.length;

    switch (keys) {
      case '·'://点击小数点，（注意输入字符串里的是小数点，但是我界面显示的点不是小数点，是居中的点，在中文输入法下按键盘最左边从上往下数的第二个键，也就是数字键1左边的键可以打出居中的点）
        if (len < 11 && content.indexOf('.') == -1) {//如果字符串里有小数点了，则不能继续输入小数点，且控制最多可输入10个字符串
          if (content.length < 1) {//如果小数点是第一个输入，那么在字符串前面补上一个0，让其变成0.
            content = '0.';
          } else {//如果不是第一个输入小数点，那么直接在字符串里加上小数点
            content += '.';
          }
        }
        break;
      case '<'://如果点击删除键就删除字符串里的最后一个
        content = content.substr(0, content.length - 1);
        break;
      default:
        let Index = content.indexOf('.');//小数点在字符串中的位置
        if (Index == -1 || len - Index != 3) {//这里控制小数点只保留两位
          if (len < 11) {//控制最多可输入10个字符串
            content += keys;
          }
        }
        break
    }
    this.setData({
      [`form.supplierPhone`]: content,
     });
  },
  stopPrice(){
    this.setData({
      isShowSheet: false,
    })
  },
  __closeMaster() {
    var that = this;
    this.contentAnimate.top("0%").step();
    this.masterAnimate.opacity(0).step();
    this.setData({
      contentAnimate: this.contentAnimate,
      masterAnimate: this.masterAnimate,
    });
    setTimeout(function() {
      that.setData({
        isShowSheet: false,
      })
    }, 200)
  },
  __showMaster() {
    //创建动画  展开
    this.setData({
      isShowSheet: true,
    });
    // 容器上弹
    var contentAnimate = wx.createAnimation({
      duration: 100,
    })
    contentAnimate.top(`-${this.properties.tops}`).step();
    //master透明度
    var masterAnimate = wx.createAnimation({
      duration: 200,
    })
    masterAnimate.opacity(.5).step();
    this.contentAnimate = contentAnimate;
    this.masterAnimate = masterAnimate;
    this.setData({
      contentAnimate: contentAnimate,
      masterAnimate: masterAnimate,
    })
  },
  numTypeClick(e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      activeName: name
    });
  },
  getList() {
    getLineList('').then(res => {
      var arr = [{
        id: 0,
        lineName: '请选择'
      }];
      arr = arr.concat(res.data);
      this.setData({
        lineList: arr
      });
      if (this.data.options.type) {
        this.getInfo(this.data.options.id);
      }
    }).catch(err => {

    })
  },
});